package com.ysd.util;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {

	private static Properties props = new Properties();
	private static String MyEmailAccount = "973898525@qq.com";// 发送邮件的邮箱
// 重点是这个，这个是在你qq邮箱里开启的一个smtp服务，要自己到qq邮箱开启获取的，而不是qq登录密码
	private static String myEamilPassword = "tspqhuomnuuvbdei";// token秘钥
	private static String MyEmailSMTPHost = "smtp.qq.com";
	private static String SMTP = "smtp";
	private static int port = 587;
	private static String defaultEncoding = "UTF-8";

	static {
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", MyEmailSMTPHost);
		props.put("mail.user", MyEmailAccount);
		props.put("mail.password", myEamilPassword);
	}
	static Authenticator authenticator = new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			// 用户名、密码
			String userName = props.getProperty("mail.user");
			String password = props.getProperty("mail.password");
			return new PasswordAuthentication(userName, password);
		}
	};

	public static boolean sendEmailCode(String to, String titles, String html) throws MessagingException {
		boolean flag = true;
		Session mailSession = Session.getInstance(props, authenticator);
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
		message.setFrom(form);
		// 设置收件人
		InternetAddress toUser = new InternetAddress(to);
		message.setRecipient(RecipientType.TO, toUser);
		// 设置邮件标题
		message.setSubject(titles);
		// 设置邮件的内容体
		message.setContent(html, "text/html;charset=UTF-8");
		// 发送邮件
		Transport.send(message);
		return flag;
	}

//	public void SendCodeToEmail(String userEmail,int code) throws MessagingException{
//		String to = "userEmail";
//		String html = "你接收的验证码为："+code+",请你及时回复。";
//		String titles = "给你福利";
//		boolean flag = sendEmailCode(to,titles,html);
//		if(flag){
//			System.out.println("发送成功！");
//		}else{
//			System.out.println("发送失败！");
//		}
//	}
}